package com.csu.csumall.controller.frontend;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csu.csumall.VO.CategoryTreeVO;
import com.csu.csumall.common.ItemStatus;
import com.csu.csumall.common.UniformResponse;
import com.csu.csumall.entity.Category;
import com.csu.csumall.service.ICategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

import static com.csu.csumall.common.Constant.ORIGIN;

@Slf4j
@RestController
@RequestMapping(value = "/api/category")
@CrossOrigin(origins = ORIGIN)
public class CategoryController {

    private final ICategoryService categoryService;

    @Autowired
    public CategoryController(ICategoryService categoryService) {
        this.categoryService = categoryService;
    }

    @GetMapping
    public UniformResponse getCategoryTree(@RequestParam(value = "parent", required = false) Integer parent) {
//        log.info("CategoryController -> getCategoryTree");
        List<CategoryTreeVO> categoryTreeVOList = new ArrayList<>();
        if (null == parent) {

            // 一级标签
            List<Category> categoryListLevel1 = categoryService.list(new QueryWrapper<Category>()
                    .eq("parent_id", 0).ne("status", ItemStatus.DISABLE.getValue()));
            categoryListLevel1.forEach(category -> {
                category.setCreateTime(null);
                category.setUpdateTime(null);
                categoryTreeVOList.add(new CategoryTreeVO(category, new ArrayList<>()));
            });

            // 二级标签
            categoryTreeVOList.forEach(categoryTreeVO -> {
                Integer id = categoryTreeVO.getCategory().getId();
                List<Category> categoryListLevel2 = categoryService.list(new QueryWrapper<Category>()
                        .eq("parent_id", id).ne("status", ItemStatus.DISABLE.getValue()));
                categoryListLevel2.forEach(category -> {
                    category.setCreateTime(null);
                    category.setUpdateTime(null);
                    categoryTreeVO.getCategoryTreeVOList().add(new CategoryTreeVO(category, new ArrayList<>()));
                });
            });

        } else {

            List<Category> categoryListLevel1 = categoryService.list(new QueryWrapper<Category>()
                    .eq("parent_id", parent).ne("status", ItemStatus.DISABLE.getValue()));
            categoryListLevel1.forEach(category -> {
                category.setCreateTime(null);
                category.setUpdateTime(null);
                categoryTreeVOList.add(new CategoryTreeVO(category, new ArrayList<>()));
            });

        }

        return UniformResponse.createForSuccess(categoryTreeVOList);
    }
}
